<template>
  <div class="admin-pets">
    <div class="container">
      <h1 class="page-title">宠物管理</h1>
      
      <div class="admin-actions">
        <el-input
          placeholder="搜索宠物..."
          v-model="searchQuery"
          class="search-input"
          prefix-icon="el-icon-search"
          clearable
          @input="handleSearch"
        >
          <template #append>
            <el-tooltip content="支持搜索名称、类别、品种和性别，按优先级排序">
              <i class="el-icon-question"></i>
            </el-tooltip>
          </template>
        </el-input>
        
        <el-button type="primary" @click="$router.push('/admin/pets/add')">
          <i class="el-icon-plus"></i> 添加宠物
        </el-button>
      </div>
      
      <el-tabs v-model="activeTab" @tab-click="handleTabClick">
        <el-tab-pane label="全部宠物" name="all"></el-tab-pane>
        <el-tab-pane label="可领养" name="available"></el-tab-pane>
        <el-tab-pane label="已申请" name="pending"></el-tab-pane>
        <el-tab-pane label="已领养" name="adopted"></el-tab-pane>
      </el-tabs>

      <el-card class="pets-table-card" v-loading="loading">
        <template v-if="filteredPets.length > 0">
          <el-table
            :data="filteredPets"
            style="width: 100%"
            border
            stripe
            :default-sort="{ prop: 'created_at', order: 'descending' }"
          >
            <el-table-column prop="id" label="ID" width="70" sortable />
            
            <el-table-column prop="name" label="名称" sortable>
              <template #default="scope">
                <div class="pet-info">
                  <el-image 
                    :src="getPetImageUrl(scope.row)" 
                    fit="cover"
                    class="pet-thumbnail"
                    @click="viewPet(scope.row.id)"
                  >
                    <template #error>
                      <div class="image-placeholder">
                        <i class="el-icon-picture-outline"></i>
                      </div>
                    </template>
                  </el-image>
                  <span>{{ scope.row.name }}</span>
                </div>
              </template>
            </el-table-column>
            
            <el-table-column prop="category" label="类别" sortable>
              <template #default="scope">
                {{ scope.row.category_name || '未知' }}
              </template>
            </el-table-column>
            
            <el-table-column prop="breed" label="品种" width="120">
              <template #default="scope">
                {{ scope.row.breed || '未知' }}
              </template>
            </el-table-column>
            
            <el-table-column prop="age" label="年龄" width="80" sortable>
              <template #default="scope">
                {{ scope.row.age ? `${scope.row.age} 岁` : '未知' }}
              </template>
            </el-table-column>
            
            <el-table-column prop="gender" label="性别" width="80">
              <template #default="scope">
                {{ formatGender(scope.row.gender) }}
              </template>
            </el-table-column>
            
            <el-table-column prop="status" label="状态" width="100" sortable>
              <template #default="scope">
                <el-tag :type="getStatusType(scope.row.status || scope.row.is_adopted)">
                  {{ formatStatus(scope.row.status || scope.row.is_adopted) }}
                </el-tag>
              </template>
            </el-table-column>
            
            <el-table-column 
              prop="created_at" 
              label="添加时间" 
              width="180" 
              sortable
            >
              <template #default="scope">
                {{ formatDate(scope.row.created_at) }}
              </template>
            </el-table-column>
            
            <el-table-column label="操作" width="130">
              <template #default="scope">
                <el-dropdown trigger="hover" @command="(command) => handleCommand(command, scope.row)" placement="bottom">
                  <el-button size="small" type="primary" plain class="action-button">
                    操作<i class="el-icon-arrow-down el-icon--right"></i>
                  </el-button>
                  <template #dropdown>
                    <el-dropdown-menu>
                      <el-dropdown-item command="view" icon="el-icon-view">查看详情</el-dropdown-item>
                      <el-dropdown-item command="edit" icon="el-icon-edit" class="edit-action">编辑</el-dropdown-item>
                      <el-dropdown-item command="delete" icon="el-icon-delete" class="delete-action" divided>删除</el-dropdown-item>
                    </el-dropdown-menu>
                  </template>
                </el-dropdown>
              </template>
            </el-table-column>
          </el-table>
          
          <div class="pagination-container" v-if="pagination.totalPages > 1">
            <el-pagination
              background
              layout="sizes, prev, pager, next"
              :total="pagination.total"
              :page-size="pageSize"
              :page-sizes="[5, 10, 20, 50]"
              :current-page="currentPage"
              @current-change="handlePageChange"
              @size-change="handleSizeChange"
            />
          </div>
        </template>
        
        <el-empty 
          v-else 
          description="没有找到宠物数据" 
          :image-size="200"
        ></el-empty>
      </el-card>
    </div>
  </div>
</template>

<script>
import { ref, computed, onMounted, watch } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';
import { useStore } from 'vuex';
import axios from 'axios';
import { getImageUrl } from '@/utils/image';
import { debounce } from 'lodash';

export default {
  name: 'AdminPets',
  setup() {
    const store = useStore();
    const router = useRouter();
    const API_URL = '/api';
    
    // 状态
    const loading = ref(false);
    const pets = ref([]);
    const pagination = ref({
      total: 0,
      page: 1,
      limit: 10,
      totalPages: 0
    });
    const categories = ref([]);
    const searchQuery = ref('');
    const activeTab = ref('all');
    const currentPage = ref(1);
    const pageSize = ref(10);
    
    // 获取认证头
    const authHeader = {
      headers: {
        Authorization: `Bearer ${store.getters['auth/token']}`
      }
    };
    
    // 根据状态过滤宠物
    const filteredPets = computed(() => {
      return pets.value;
    });
    
    // 加载所有宠物
    const loadPets = async () => {
      loading.value = true;
      try {
        // 准备请求参数
        const params = {
          page: currentPage.value,
          limit: pageSize.value
        };
        
        // 不在API请求中添加过滤条件，获取所有宠物数据
        // 将在客户端进行过滤
        
        const response = await axios.get(`${API_URL}/pets`, {
          params,
          headers: {
            ...authHeader.headers,
            'Content-Type': 'application/json'
          }
        });
        
        if (response.data && response.data.pets) {
          let petsData = response.data.pets;
          
          // 如果有搜索关键词，在客户端进行搜索过滤
          if (searchQuery.value.trim()) {
            const query = searchQuery.value.trim().toLowerCase();
            
            // 根据优先级顺序搜索：名称 > 类别 > 品种 > 性别
            const matchByName = petsData.filter(pet => 
              pet.name && pet.name.toLowerCase().includes(query)
            );
            
            const matchByCategory = petsData.filter(pet => 
              pet.category_name && pet.category_name.toLowerCase().includes(query) &&
              !matchByName.some(p => p.id === pet.id)
            );
            
            const matchByBreed = petsData.filter(pet => 
              pet.breed && pet.breed.toLowerCase().includes(query) &&
              !matchByName.some(p => p.id === pet.id) &&
              !matchByCategory.some(p => p.id === pet.id)
            );
            
            const matchByGender = petsData.filter(pet => {
              const genderText = formatGender(pet.gender).toLowerCase();
              return genderText.includes(query) &&
                !matchByName.some(p => p.id === pet.id) &&
                !matchByCategory.some(p => p.id === pet.id) &&
                !matchByBreed.some(p => p.id === pet.id);
            });
            
            // 合并搜索结果，保持优先级顺序
            petsData = [...matchByName, ...matchByCategory, ...matchByBreed, ...matchByGender];
          }
          
          // 根据选择的标签过滤宠物
          if (activeTab.value === 'available') {
            petsData = petsData.filter(pet => !pet.is_adopted && pet.status !== 'pending');
          } else if (activeTab.value === 'pending') {
            petsData = petsData.filter(pet => pet.status === 'pending');
          } else if (activeTab.value === 'adopted') {
            petsData = petsData.filter(pet => pet.is_adopted);
          }
          
          pets.value = petsData;
          
          // 更新分页信息
          pagination.value = {
            total: petsData.length,
            page: currentPage.value,
            limit: pageSize.value,
            totalPages: Math.ceil(petsData.length / pageSize.value)
          };
          
          // 如果当前页码超过了总页数，回到第一页
          if (currentPage.value > pagination.value.totalPages && pagination.value.totalPages > 0) {
            currentPage.value = 1;
          }
        } else {
          pets.value = [];
          pagination.value = {
            total: 0,
            page: 1,
            limit: pageSize.value,
            totalPages: 0
          };
        }
      } catch (error) {
        ElMessage.error('加载宠物数据失败');
        pets.value = [];
        pagination.value = {
          total: 0,
          page: 1,
          limit: pageSize.value,
          totalPages: 0
        };
      } finally {
        loading.value = false;
      }
    };
    
    // 加载分类数据
    const loadCategories = async () => {
      try {
        // 使用正确的API路径获取类别数据
        const response = await axios.get(`${API_URL}/pets/categories`);
        if (response.data && Array.isArray(response.data)) {
          categories.value = response.data;
        } else {
          categories.value = [];
        }
      } catch (error) {
        categories.value = []; // 设置为空数组而不是显示错误
      }
    };
    
    // 获取分类名称
    const getCategoryName = (categoryId) => {
      if (!categoryId) return '未分类';
      if (!categories.value || categories.value.length === 0) {
        return '未知分类';
      }
      
      // 尝试转换categoryId为数字
      let id = categoryId;
      try {
        id = parseInt(categoryId);
      } catch (e) {
        // 忽略解析错误
      }
      
      const category = categories.value.find(c => c.id === id);
      
      if (category) {
        return category.name;
      } else {
        return '未知分类';
      }
    };
    
    // 获取宠物图片URL
    const getPetImageUrl = (pet) => {
      if (!pet.image_url) return 'https://via.placeholder.com/100x100?text=No+Image';
      
      // 检查图片URL是否已经是完整URL
      if (pet.image_url.startsWith('http')) {
        return pet.image_url;
      }
      
      // 使用相对路径（将通过代理访问）
      const path = pet.image_url.startsWith('/') ? pet.image_url : `/${pet.image_url}`;
      return path;
    };
    
    // 格式化日期
    const formatDate = (dateString) => {
      const options = { 
        year: 'numeric', 
        month: 'numeric', 
        day: 'numeric',
        hour: '2-digit',
        minute: '2-digit'
      };
      return new Date(dateString).toLocaleDateString('zh-CN', options);
    };
    
    // 格式化性别
    const formatGender = (gender) => {
      const genderMap = {
        'male': '公',
        'female': '母',
        'unknown': '未知'
      };
      return genderMap[gender] || '未知';
    };
    
    // 格式化状态
    const formatStatus = (status) => {
      // 根据状态字段和is_adopted字段共同决定显示的状态
      if (status === 'pending') {
        return '已申请';
      } else if (status === 'adopted' || status === true) {
        return '已领养';
      } else {
        return '可领养';
      }
    };
    
    // 获取状态类型
    const getStatusType = (status) => {
      if (status === 'pending') {
        return 'warning';
      } else if (status === 'adopted' || status === true) {
        return 'info';
      } else {
        return 'success';
      }
    };
    
    // 处理标签页切换
    const handleTabClick = () => {
      currentPage.value = 1;
      loadPets();
    };
    
    // 处理页面变化
    const handlePageChange = (page) => {
      currentPage.value = page;
      loadPets();
    };
    
    // 处理每页显示数量变化
    const handleSizeChange = (size) => {
      pageSize.value = size;
      currentPage.value = 1; // 重置到第一页
      loadPets();
    };
    
    // 查看宠物详情
    const viewPet = (id) => {
      router.push(`/pets/${id}`);
    };
    
    // 编辑宠物
    const editPet = (id) => {
      router.push(`/admin/pets/${id}/edit`);
    };
    
    // 删除宠物
    const deletePet = async (pet) => {
      try {
        await ElMessageBox.confirm(`确定要删除宠物 "${pet.name}" 吗?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        });
        
        loading.value = true;
        
        // 检查是否存在关联的申请
        try {
          const checkResponse = await axios.get(`${API_URL}/adoptions/pet/${pet.id}/applications/count`, {
            headers: authHeader.headers
          });
          
          if (checkResponse.data && checkResponse.data.count > 0) {
            // 有关联申请，再次确认
            await ElMessageBox.confirm(
              `该宠物有${checkResponse.data.count}个领养申请记录，删除宠物将同时删除相关申请记录。确定继续吗？`, 
              '警告', 
              {
                confirmButtonText: '继续删除',
                cancelButtonText: '取消',
                type: 'warning'
              }
            );
          }
        } catch (checkError) {
          // 如果请求失败，可能是路由不存在，忽略错误继续删除
          if (checkError.response && checkError.response.status !== 404) {
            console.error('检查宠物申请记录失败:', checkError);
          }
        }
        
        // 执行删除操作
        await axios.delete(`${API_URL}/pets/${pet.id}`, {
          headers: authHeader.headers
        });
        
        ElMessage.success('宠物删除成功');
        
        // 重新加载数据
        await loadPets();
      } catch (error) {
        if (error !== 'cancel' && error !== 'close') {
          // 处理删除错误
          if (error.response) {
            const statusCode = error.response.status;
            const errorMessage = error.response.data?.message || '未知错误';
            
            if (statusCode === 403) {
              ElMessage.error('您没有权限删除此宠物');
            } else if (statusCode === 404) {
              ElMessage.warning('宠物不存在，可能已被删除');
              // 刷新列表
              loadPets();
            } else if (statusCode === 500) {
              ElMessage.error(`服务器错误: ${errorMessage}`);
            } else {
              ElMessage.error(`删除宠物失败: ${errorMessage}`);
            }
          } else if (typeof error === 'object') {
            ElMessage.error(`操作失败: ${error.message || '未知错误'}`);
          } else {
            ElMessage.error('删除操作未完成');
          }
        }
      } finally {
        loading.value = false;
      }
    };
    
    // 处理搜索输入
    const handleSearch = debounce(() => {
      currentPage.value = 1; // 重置到第一页
      loadPets();
    }, 300);
    
    // 监听搜索词变化
    watch(searchQuery, () => {
      handleSearch();
    });
    
    // 处理下拉菜单命令
    const handleCommand = (command, pet) => {
      switch(command) {
        case 'view':
          viewPet(pet.id);
          break;
        case 'edit':
          editPet(pet.id);
          break;
        case 'delete':
          deletePet(pet);
          break;
      }
    };
    
    // 组件挂载时加载数据
    onMounted(async () => {
      // 首先加载宠物数据，如果失败则至少用户可以看到页面
      await loadPets().catch(() => {
        ElMessage.error('无法加载宠物数据，请稍后重试');
      });
      
      // 然后尝试加载分类数据，但不阻止页面显示
      loadCategories();
    });
    
    return {
      loading,
      pets,
      pagination,
      categories,
      searchQuery,
      activeTab,
      currentPage,
      pageSize,
      filteredPets,
      getCategoryName,
      getPetImageUrl,
      formatDate,
      formatGender,
      formatStatus,
      getStatusType,
      handleTabClick,
      handlePageChange,
      handleSizeChange,
      handleSearch,
      handleCommand
    };
  }
}
</script>

<style lang="scss" scoped>
@use "sass:color";

.admin-pets {
  min-height: calc(100vh - 200px);
  padding: 40px 0;
}

.admin-actions {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
  
  .search-input {
    width: 300px;
  }
}

.pets-table-card {
  margin-bottom: 30px;
}

.pet-info {
  display: flex;
  align-items: center;
  
  .pet-thumbnail {
    width: 50px;
    height: 50px;
    border-radius: 4px;
    margin-right: 10px;
    overflow: hidden;
    cursor: pointer;
    
    &:hover {
      opacity: 0.8;
    }
  }
}

.image-placeholder {
  width: 40px;
  height: 40px;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #f0f0f0;
  color: #909399;
  border-radius: 4px;
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

@media (max-width: 768px) {
  .admin-actions {
    flex-direction: column;
    
    .search-input {
      width: 100%;
      margin-bottom: 10px;
    }
    
    .el-button {
      width: 100%;
    }
  }
}

// 修复图片预览层样式
:deep(.el-image-viewer__wrapper) {
  z-index: 9999 !important;
}

:deep(.el-overlay) {
  z-index: 9998 !important;
}

/* Operation button styles */
.action-button {
  min-width: 80px;
}

.edit-action {
  color: #e6a23c;
}

.edit-action:hover {
  background-color: #fdf6ec;
}

.delete-action {
  color: #f56c6c;
}

.delete-action:hover {
  background-color: #fef0f0;
}
</style> 